import { Controller, App, Post, Body } from "@midwayjs/core";
import { Application } from "../interface.js";
import { failres, okres } from "../config/resUtil.js";
import { log } from "console";
import fs from "fs";
import { cloneDeep, lodashMap as map, template as lodashTemplate } from "lodash-es";
import { Query_dto } from "../models/query.dto.js";
import path from "path";
import compressing from "compressing";
import { getdb } from "../config/initdb.js";
import { Datasource_dto } from "../models/datasource.dto.js";
import { Parser } from "sql-ddl-to-json-schema";
const parser = new Parser('mysql');

@Controller("/api/gerenrate")
export class GenerateController {
  @App("koa")
  app: Application;

  @Post("/apis")
  async apis(@Body() body) {
    var funname = body?._name;
    var func = this?.[funname];
    if (!func) {
      return failres(funname + "404");
    }

    var _params = cloneDeep(body);
    delete _params._name;
    delete _params["模块"];

    var _func = func.bind(this);
    return _func(_params);


  }

  //加压文件夹
  async jieyarar(options) {
    // //rar 文件
    // var templatePath=options?.templatePath
    // //解压到  distPath
    // var distPath=options?.distPath;

    // await fs.unlinkSync(distPath+'\\src');
    // var result=await   compressing.gzip.uncompress(templatePath,distPath)
    // console.log('解压的结果  result :', result);
    // return result
  }

  gettstypes(type) {
    if (type?.indexOf("int") >= 0) {
      return "Number";
    } else if (type?.indexOf("varcha") >= 0) {
      return "String";
    } else if (type?.indexOf("datetime") >= 0) {
      return "Date";
    }
    return "String";
  }

  async 生产代码(body) {
    var self = this;
    console.log("开始 生产代码 :");

    console.log("body?.tableName :", body?.tableName);

    var 后端端口 = body?.后端端口;
    console.log("【参数】后端端口 :", 后端端口);


    //validate
    if (!body?.tableName) {
      return failres("没有 参数  tableName");
    }


    var keylistresult = await this.keydescription(body);
    var keylist = keylistresult && keylistresult.data || [];
    console.log("keylist :", keylist);


    //解压文件
    // var resultcontroller = await this.jieyarar({
    //     templatePath: 'e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\template.tar.gz',
    //     distPath: 'E:\\home\\demo05\\test01',
    // })


    //生 后端代码
    var resultcontroller1 = await this.makeStr({
      templatePath: "e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\controller.template.tpl",
      tableName: body?.tableName,
      distPath: "E:\\home\\demo05\\eggjj\\midway-project\\src\\controller\\generate\\" + body?.tableName + ".controller.ts",
      data: {
        tableName: body?.tableName,
        colkeys: keylist,
        datasourceDto: body?.datasourceDto

      }
    });

    var resultcontroller1 = await this.makeStr({
      templatePath: "e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\controllerplus.template.tpl",
      tableName: body?.tableName,
      distPath: "E:\\home\\demo05\\eggjj\\midway-project\\src\\controller\\" + body?.tableName + "plus.controller.ts",
      nooverwrite: true,
      data: {
        tableName: body?.tableName,
        colkeys: keylist,
        datasourceDto: body?.datasourceDto

      }
    });


    // var resultcontroller2 = await this.makeStr({
    //     templatePath: 'e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\models.template.tpl',
    //     tableName: body?.tableName,
    //     distPath: 'E:\\home\\demo05\\test01\\src\\models\\' + body?.tableName + '.dto.ts',
    //     data: {
    //         tableName: body?.tableName,
    //         colkeys: keylist,

    //     }
    // })


    // 默认配置
    // var resultcontroller3 = await this.makeStr({
    //     templatePath: 'e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\config.default.tpl',
    //     tableName: body?.tableName,
    //     distPath: 'E:\\home\\demo05\\test01\\src\\config\\config.default.ts',
    //     data: {
    //         tableName: body?.tableName,
    //         后端端口,
    //         datasourceDto:body?.datasourceDto,
    //     }
    // })


    //  initdb.ts
    // var resultcontroller4 = await this.makeStr({
    //     templatePath: 'e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\initdb.tpl',
    //     tableName: body?.tableName,
    //     distPath: 'E:\\home\\demo05\\test01\\src\\config\\initdb.ts',
    //     data: {
    //         tableName: body?.tableName,
    //         后端端口
    //     }
    // })


    //开始生产前端代码 list  modify
    var resultcontroller5 = await this.makeStr({
      templatePath: "e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\vue\\list.vue",
      tableName: body?.tableName,
      distPath: "E:\\home\\demo05\\eggjj\\my-vue-app\\src\\views\\" + body?.tableName + "\\list.vue",
      nooverwrite: true,
      data: {
        tableName: body?.tableName,
        colkeys: keylist,
        datasourceDto: body?.datasourceDto
      }
    });

    var resultcontroller5 = await this.makeStr({
      templatePath: "e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\vue\\modify.vue",
      tableName: body?.tableName,
      distPath: "E:\\home\\demo05\\eggjj\\my-vue-app\\src\\views\\" + body?.tableName + "\\modify.vue",
      nooverwrite: true,
      data: {
        tableName: body?.tableName,
        colkeys: keylist,
        datasourceDto: body?.datasourceDto
      }
    });


    var resultcontroller6 = await this.makeStr({
      templatePath: "e:\\home\\demo05\\eggjj\\midway-project\\resources\\generate\\vue\\_utils.js",
      tableName: body?.tableName,
      distPath: "E:\\home\\demo05\\eggjj\\my-vue-app\\src\\views\\" + body?.tableName + "\\_utils.js",
      data: {
        tableName: body?.tableName,
        colkeys: keylist,
        datasourceDto: body?.datasourceDto
      }
    });


    return okres(resultcontroller1);

  }


  getdbname(datasourceDto: Datasource_dto) {
    console.log("[getdbname]  :", datasourceDto);
    if (datasourceDto.type == "sqlite") {
      return "sqiltedb";
    }
    ;

    if (datasourceDto?.database == "szq_erp") {
      return "erpdb";
    }
    if (datasourceDto?.database == "szq_mes") {
      return "mesdb";
    }
    if (datasourceDto?.database == "szq_system") {
      return "systemdb";
    }
  }

  async makeStr(options) {
    var distPath = options?.distPath;
    var templatePath = options?.templatePath;
    var _data = options?.data;
    var tableName = _data?.tableName || _data?.tablename;

    //是否 不覆盖  默认覆盖
    var nooverwrite = options?.nooverwrite;


    if (!distPath) {
      return failres("生成的路径（含名称） 必填");
    }

    if (!templatePath) {
      return failres("模板路径（含名称） 必填");
    }

    if (!tableName) {
      return failres("表名称 必填");
    }

    var controllerTemplate = await fs.readFileSync(`${templatePath}`);
    var controllerstr = lodashTemplate(controllerTemplate)({
      tableName: tableName,
      colkeys: _data?.colkeys || [],
      gettstypes: this.gettstypes,
      后端端口: _data?.后端端口,
      datasourceDto: _data?.datasourceDto,
      getdbname: this.getdbname
    });


    //指定一个位置 controller
    var controlelrpath = `${distPath}`;
    await this.mkdirRecursive(controlelrpath);

    if (nooverwrite) {
      if (!fs.existsSync(controlelrpath)) {
        var result1 = await fs.writeFileSync(controlelrpath, controllerstr);
        return okres(result1);
      }
    } else {
      var result1 = await fs.writeFileSync(controlelrpath, controllerstr);
      return okres(result1);
    }

  }


  async keydescription(body: Query_dto): Promise<any> {
    var db = await getdb(body.datasourceDto);
    // var inert_result=await knex('tb_books').insert({title: 'Slaughterhouse Five'})
    var pageNum = body?.pageSize || 10;
    var tableName = body?.tableName;
    var offset = ((body?.pageNum || 1) - 1) * pageNum;
    if (!tableName) {
      return failres("[tableName] is required");
    }

    var onelist = [];
    if (body?.datasourceDto.type == "sqlite") {
      // select count(*)  from sqlite_master wheretype='table' and name = 'yourtablename';
      var queryBuilder = await db.raw(`PRAGMA  table_info('${tableName}')`);
      onelist = queryBuilder.map(item => {
        return {
          Field: item.name,
          Type: item.type
        };
      });
      console.log("sqlite ==>onelist :", onelist);
    } else {
      var queryForm = body?.queryForm;
      var queryBuilder = await db.raw(`SHOW FULL COLUMNS FROM ${tableName};`);
      onelist = queryBuilder?.[0];
    }


    return okres(onelist);

  }


  async mkdirRecursive(path) {
    if (path.indexOf(".ts") >= 0 || path.indexOf(".vue") >= 0) {
      path = path.substring(0, path.lastIndexOf("\\"));
    }
    console.log("【【mkdirRecursive】】path :", path);
    const directory = path.substring(0, path.lastIndexOf("\\"));
    console.log("【mkdirRecursive】 directory :", directory);
    if (!fs.existsSync(directory)) {
      await this.mkdirRecursive(directory);
    }
    if (!fs.existsSync(path)) {
      await fs.mkdirSync(path);
    }

  }


  //使用 ddl 获取 schemas
  @Post("/getscehemasbyddl")
  async getscehemasbyddl(@Body() body: { ddl: string }) {
    var ddl = body?.ddl;
    if (!ddl) {
      return failres("请输入ddl");
    }
    const options = { useRef: false };
    parser.feed(ddl);
    const parsedJsonFormat = parser.results;
    const compactJsonTablesArray = parser.toCompactJson(parsedJsonFormat);
    const jsonSchemaDocuments = parser.toJsonSchemaArray(options, compactJsonTablesArray);
return okres(jsonSchemaDocuments)

  }

}
